<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <el-form
      ref="searchFormRef"
      :model="queryParams"
      :inline="true"
      class="globalSerchFormStyle"
    >
      <el-row>
        <el-col :span="6" v-if="authUser">
          <el-form-item label="油企名称" prop="enterpriseId">
            <el-select
              v-model="queryParams.enterpriseId"
              placeholder="请选择油企"
              size="small"
              filterable
              clearable
              style="width: 190px"
              @change="handleSelectChange"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :label="item.enterpriseName"
                :value="item.enterpriseId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="油站名称" prop="stationId">
            <el-select
              v-model="queryParams.stationId"
              placeholder="请选择油站"
              size="small"
              filterable
              clearable
              style="width: 190px"
            >
              <el-option
                v-for="item in stationList"
                :key="item.stationId"
                :label="item.stationName"
                :value="item.stationId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="queryParams.name"
              size="small"
              placeholder="请输入商品名称"
              clearable
              style="width: 190px"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品ID" prop="id">
            <el-input
              v-model="queryParams.id"
              size="small"
              placeholder="请输入商品ID"
              clearable
              style="width: 190px"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <div v-show="collapse">
        <el-row>
          <el-col :span="6">
            <el-form-item label="商品状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                size="small"
                clearable
                style="width: 190px"
              >
                <el-option label="待上架" value="1"></el-option>
                <el-option label="已下架" value="2"></el-option>
                <el-option label="在售" value="3"></el-option>
                <el-option label="已售空" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间" prop="createdTime">
              <el-date-picker
                v-model="dataTimeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
                value-format="yyyy-MM-dd HH:mm:ss"
                clearable
                style="width: 190px"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="getNonGoogsList"
        >
          搜索
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handelRestQueryForm"
          icon="el-icon-refresh"
          plain
        >
          重置
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="default" size="mini" @click="collapse = !collapse">
          {{ collapse ? "收起" : "展开更多" }}
          <i :class="collapse ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          @click="handleAddOrEdit('add', {})"
          icon="el-icon-plus"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          plain
          :disabled="!multipleSelection.length"
          icon="el-icon-delete"
          @click="delNonOilDialogVisible = true"
          >删除</el-button
        >
      </el-col>
    </el-row>
    <!--表格 -->
    <el-table
      stripe
      v-loading="loading"
      ref="multipleTable"
      :data="oiltableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column
        v-if="authUser"
        prop="enterpriseName"
        label="油企名称"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="stationName"
        label="油站名称"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="商品名称"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="id" label="商品ID" show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="描述"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="consumedPoint"
        label="消耗积分"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="stock"
        label="库存"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="status" label="商品状态" show-overflow-tooltip>
        <template v-slot="{ row }">
          <span
            v-if="row.status === 3"
            style="color: black; letter-spacing: 15px"
            >在售</span
          >
          <span v-if="row.status === 4" style="color: lightgray">已售空</span>
          <span v-if="row.status === 2" style="color: red">已下架</span>
          <span v-if="row.status === 1">待上架</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdTime"
        label="创建时间"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop=""
        label="操作"
        show-overflow-tooltip
        fixed="right"
        width="200"
      >
        <template v-slot="{ row }">
          <el-button type="text" @click="handleAddOrEdit('detail', row)"
            >查看</el-button
          >
          <el-button type="text" @click="handleAddOrEdit('edit', row)">
            编辑
          </el-button>
          <el-button
            type="text"
            v-if="row.status === 1"
            @click="handleUpOrDownGood(row, '上架')"
          >
            上架
          </el-button>
          <el-button
            type="text"
            v-if="row.status === 3 || row.status === 4"
            @click="handleUpOrDownGood(row, '下架')"
          >
            下架
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页(全局组件) -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :autoScroll="true"
      @pagination="getNonGoogsList"
    />

    <!-- 添加或编辑抽屉 -->
    <DeptNonOilDrawer
      :drawerVisible.sync="drawerVisible"
      :title="title"
      :operationType="operationType"
      :currentRowData="currentRowData"
      @resetCurrentRowData="resetCurrentRowData"
      @reloadData="getNonGoogsList"
    ></DeptNonOilDrawer>
    <!-- 删除商品对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="delNonOilDialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>确定删除所选商品吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delNonOilDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delGoodInfoList">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 上架或下架对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="upOrDownNonOilDialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>{{ upOrdowntitle }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="upOrDownNonOilDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="changeGoodStatus">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import DeptNonOilDrawer from "./Dept_Non_Oil_Drawer.vue";
import {
  getNonGoogsListApi,
  getEnterpriseList,
  listEnterpriseStation,
  changeNonOilGoodStatusApi,
  delNonOilGoodsApi,
} from "@/api/dept";
import { getToken } from "@/utils/auth";
export default {
  name: "DeptNonOilManagement",
  components: { DeptNonOilDrawer },
  data() {
    return {
      total: 10,
      loading: false,
      collapse: false, //是否展开剩余搜索项
      title: "新增非油品商品",
      multipleSelection: [], // 多选
      currentRowData: {}, // 当前行数据
      dataTimeRange: [], // 创建时间范围
      drawerVisible: false, // 控制右侧抽屉是否显示
      formLabelWidth: "80px",
      oiltableData: [], // 非油品列表
      enterpriseList: [], // 油企列表
      stationList: [], //油站列表
      delNonOilDialogVisible: false, // 控制删除上坪对话框
      upOrDownNonOilDialogVisible: false, // 上架或下架对话框
      upOrdowntitle: "上架", // 弹框标题
      operationType: "add", // 操作类型  add ， edit，  detail
      // 查询参数
      queryParams: {
        pageNum: 1, // 页码
        pageSize: 10,
        stationId: null, // 油站id
        enterpriseId: null, // 油企id
        enterpriseName: "", // 油企名称
        name: "", //商品名称
        id: null, // 商品ID
        status: "", // 商品状态 状态(1:待上架 2:已下架 3:在售 4:已售空)
        createdTime: "",
        beginTime: "",
        endTime: "",
      },
      // 添加或编辑商品
      goodsForm: {
        name: "", // 商品名称
        consumedPoint: "", //消耗积分
        stock: "", // 库存
        remark: "", //描述
        enterpriseId: "", // 油企id
        stationId: "", // 油站id
        image: "", // 图片字符串
      },
      // 表单校验规则
      goodsFormRules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        consumedPoint: [
          { required: true, message: "请输入兑换所需积分", trigger: "blur" },
        ],
        stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
        enterpriseId: [
          { required: true, message: "请选择油站", trigger: "change" },
        ],
        stationId: [
          { required: true, message: "请选择油站名称", trigger: "change" },
        ],
      },
      imgUpConfig: {
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        addressUrl: process.env.VUE_APP_BASE_API + "/common/upload",
        // limit: 2,
      },
      currentUpOrDownIfo: {
        id: "", // 商品id
        status: "", // 状态
      },
    };
  },
  computed: {
    authUser() {
      // 判断用户是否是admin账号
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
  },
  created() {
    // 获取非油品列表
    this.getNonGoogsList();
    // 获取油企列表
    this.getEnterpriseList();
    // 如果当前是油企账号，则获取该企业下的油站  presentEnterprise是全局的对象数据
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getStationList(this.presentEnterprise.enterpriseId);
    }
  },
  methods: {
    // 查询油企
    getEnterpriseList() {
      getEnterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },

    // 改变切换油企时
    handleSelectChange(val) {
      this.queryParams.stationId = null;
      this.getStationList(val);
    },

    // 获取油站列表
    async getStationList(enterpriseId) {
      const res = await listEnterpriseStation({ enterpriseId: enterpriseId });
      this.stationList = res;
    },

    // 重置查询条件表单
    handelRestQueryForm() {
      this.dataTimeRange = [];
      this.resetForm("searchFormRef");
      this.getNonGoogsList();
    },

    // 获取非油品列表
    async getNonGoogsList() {
      let params = this.queryParams;
      // 如果是油企账号或油站账号，则获取当前登录账号对应油企下的数据
      if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
        params.enterpriseId = this.presentEnterprise.enterpriseId;
      }
      if (this.dataTimeRange && this.dataTimeRange.length) {
        params = {
          ...this.queryParams,
          beginTime: this.dataTimeRange[0],
          endTime: this.dataTimeRange[1],
        };
      }
      this.loading = true;
      const res = await getNonGoogsListApi(params);
      this.oiltableData = res.rows;
      this.total = res.total;
      this.loading = false;
    },

    // 新增或编辑
    async handleAddOrEdit(action, data) {
      // 打开右侧抽屉
      this.drawerVisible = true;
      this.operationType = action;
      this.currentRowData = data;
      if (action === "add") {
        this.title = "新增非油品管理";
      }
      if (action === "edit" || action === "detail") {
        this.title =
          action === "edit" ? "编辑非油品管理" : "查看非油品商品信息";
      }
    },

    handleUpOrDownGood(row, type) {
      this.currentUpOrDownIfo.id = row.id;
      this.currentUpOrDownIfo.status = row.status;
      this.upOrDownNonOilDialogVisible = true;
      this.upOrdowntitle = `确定要${type} ${row.name} 商品吗`;
    },

    // 上架，下架操作
    async changeGoodStatus(row) {
      // 状态(1:待上架 2:已下架 3:在售 4:已售空)
      const { id, status } = this.currentUpOrDownIfo;
      if (status === 1) {
        await changeNonOilGoodStatusApi(id, 3);
        this.msgSuccess("商品上架成功");
        this.getNonGoogsList();
      }
      if (status === 3 || status === 4) {
        await changeNonOilGoodStatusApi(id, 2);
        this.msgSuccess("商品下架成功");
        this.getNonGoogsList();
      }
      this.upOrDownNonOilDialogVisible = false;
    },

    // 选中多行的
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("选中了某行", val);
    },

    // 删除商品(非油品)
    async delGoodInfoList() {
      let list = this.multipleSelection;
      let ids = list.map((item) => item.id).join(",");
      await delNonOilGoodsApi(ids);
      this.msgSuccess("删除商品成功");
      this.getNonGoogsList();
      this.delNonOilDialogVisible = false;
    },

    // 关闭整个抽屉
    handleClose(done) {
      try {
        done();
      } catch (error) {
        console.log(error);
      }
    },
    // 设置当前行数据
    resetCurrentRowData() {
      console.log("重置当前行数据了？");
      this.currentRowData = {};
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-drawer__body {
  overflow: auto;
}
.demo-drawer__footer {
  text-align: end;
}
ul,
li {
  list-style: none;
}
.detail-info {
  padding: 0rem 2rem;
  dl {
    display: flex;

    dt {
      color: #606266;
      width: 80px;
      text-align: end;
      font-size: 0.9rem;
    }
    dd {
      color: #606266;
      padding-left: 1rem;
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      img {
        width: 150px;
        height: 150px;
        margin-right: 1rem;
        margin-bottom: 1rem;
        border: 1px dashed #ddd;
      }
    }
  }
}
</style>
